package com.apestech.framework.sql.lib;

import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.MultiDataBase;
import com.apestech.framework.util.StringFuncUtil;

public class DeleteSql extends StringFuncUtil {
	
	private String sql;
	private String operSql;
	private String tabname;
	private int whereStart=-1;
	
	public DeleteSql(String sql) throws Exception{
		this.sql=sql;
		this.operSql=sql.toLowerCase();
		String error=check();
		if(!"".equals(error)){
			throw new Exception(error);
		}
		getTabname();
		getSqlstructure();
	}
	
	/**
	 * 返回空串代表无错，有错返回错误信息，不会判断全表操作
	 * @return
	 */
	public String check(){
		return check(true);
	}
	
	/**
	 * 返回空串代表无错，有错返回错误信息，不会判断全表操作
	 * @return
	 */
	public String check(boolean alldata){
		try {
			checkDelete(true);
		} catch (Exception e) {
			return e.getMessage();
		} 
		return "";
	}

	/**
	 * 删除SQL有效性检查
	 * @param alldata
	 * @throws Exception
	 */
	private void checkDelete(boolean alldata) throws Exception{
		int count=this.countString(" "+this.operSql, " delete ");
		if(count>1){
			throw new Exception(getMessage("SqlPaste_errorDeleteSql","delete关键字只能有一个，实际有[({0})]个!",count));
		}
		if(!alldata){
			if(this.operSql.indexOf(" where ")<0){
				throw new Exception(getMessage("SqlPaste_errorDeleteSqlAll","不允许全表删除!"));
			}
		}
	}
	
	/**
	 * 获取操作表名
	 */
	private void getTabname(){
		if(this.operSql.indexOf(" from ")>=0){
			if(this.operSql.indexOf(" where ")>=0){
				this.tabname=this.operSql.substring(this.operSql.indexOf(" from ")+6, this.operSql.indexOf(" where ")).trim();
			} else {
				this.tabname=this.operSql.substring(this.operSql.indexOf(" from ")+6, this.sql.length()).trim();
			}
			
		} else {
			if(this.operSql.indexOf(" where ")>=0){
				this.tabname=this.operSql.substring(this.operSql.indexOf("delete ")+7, this.operSql.indexOf(" where ")).trim();
			} else {
				this.tabname=this.operSql.substring(this.operSql.indexOf("delete ")+7, this.operSql.length()).trim();
			}
			
		}
	}
	
	/**
	 * 获取表名
	 * @return
	 */
	public String getTableName(){
		return this.tabname;
	}
	
	/**
	 * 获取SQL相关结构位置信息
	 */
	private void getSqlstructure(){
		int pos=this.operSql.indexOf(" where ");
		if(pos>=0){
			this.whereStart=this.operSql.indexOf(" where ");
		} else {
			this.whereStart=this.operSql.length()-1;
		}
	}
	
	/**
	 * 获取主更新语句中的更新字段子串
	 * @return
	 * @throws Exception
	 */
	public String getDeleteTable() throws Exception{
		return this.sql.substring(0,this.whereStart+1);
	}
	
	/**
	 * 获取主更新语句中的WHERE条件子串
	 * @return
	 * @throws Exception
	 */
	public String getDeleteWhere() throws Exception{
		return this.sql.substring(this.whereStart+1, this.sql.length());
	}
	
	/**
	 * 获取更新SQL结构
	 * @return
	 * @throws Exception
	 */
	public JSONObject getSqlStructure() throws Exception{
		JSONObject map=new JSONObject();
		map.put("table", getDeleteTable());
		map.put("where", getDeleteWhere());
		return map;
	}
	
}
